# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.

import Environment
import datetime
from web_lib.page import Page
from web_lib.webutils import *
from web_lib.webutils import Response, expose , json
from dao.TipoCampo import TipoCampo
from lib.utils import mN, prep2json
from random import randint as rint

@expose('/pg/as_Campo/<action>')
@expose('/pg/as_Campo/')
@expose('/pg/as_Campo')
def anagraficaCampo(req, action=None):
    """
  id serial NOT NULL,
  denominazione_breve character varying(10) NOT NULL,
  denominazione character varying(100) NOT NULL,
  percentuale numeric(8,4) NOT NULL,
  percentuale_detrazione numeric(8,4),
  descrizione_detrazione character varying(100),
  id_tipo integer NOT NULL,
    """
    from dao.Campo import Campo

    def __show__(req, action=None):
        pageData = {'file' : "/pg/as_Campo",
                }
        return Page(req).render(pageData)
    def __list__(req, action=None):
        #Environment.session.execute("SET search_path TO {0}".format(Environment.schema))
        sorting = req.args.get("jtSorting")
        offset = req.args.get("jtStartIndex")
        batchSize = req.args.get("jtPageSize")
        fk_denominazione =  req.form.get("fk_denominazione")
        daos = Campo().select(denominazione=fk_denominazione,
                            batchSize=batchSize,
                            offset=offset,
                            orderBy=sorting)
        count = Campo().count(denominazione=fk_denominazione,
                                    batchSize=None)
        item = {
            "Result":"OK",
            "TotalRecordCount": count,
            "Records": prep2json(daos)
            }
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __create__update__(req, action=None):
        """Aggiunge una riga alle pesate"""
        id = req.form.get("id")
        if id:
            d = Campo().getRecord(id=int(id))
        else:
            d = Campo()
        d.denominazione = str(req.form.get("denominazione"))
        d.required = bool(req.form.get("required"))
        d.sensibile = bool(req.form.get("sensibile"))
        d.visibile = bool(req.form.get("visibile"))
        d.id_tipo_campo = int(req.form.get("id_tipo_campo"))
        try:
            d.persist()
            if id:
                item = {"Result":"OK"}
            else:
                item = {"Result":"OK","Record":d.jsanity()}
        except:
            item = {
                "Result":"ERROR",
                "Message": "Creazione o modifica nuova riga non riuscita"}

        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __delete__(req, action=None):
        """Cancella una riga"""
        id = int(req.form.get("id"))
        d = Campo().getRecord(id=id)
        try:
            d.delete()
            item = {"Result": "OK", }
        except:
            item = {
                "Result":"ERROR",
                "Message": "Cancellazione riga non riuscita"}
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __get_tai__(req, action=None):
        tai = TipoCampo().select(batchSize = None)
        item = {"Result":"OK",
                    "Options":[{"DisplayText":"","Value":""}]+ [{
                        "DisplayText":str(d.denominazione),
                        "Value":d.id} for d in tai]}
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    if leggiInSessione(req, sezione="Main", chiave="schema") is None:
        url_red = "/pg/main"
    elif action=="List":
        return __list__ (req, action=action)
    elif action=="show":
        return __show__(req, action=action)
    elif action=="Create" or action == "Update":
        return __create__update__(req, action=action)
    elif action=="Delete":
        return __delete__(req, action=action)
    elif action == "GetTipoCampo":
        return __get_tai__(req, action=action)
    else:
        return __show__(req, action=action)
